<template>
  <div class="login-container">
    <el-form
      ref="formRef"
      :model="loginForm"
      :rules="rules"
      label-width="80px"
      class="login-form"
    >
      <h2>用户登录</h2>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" show-password placeholder="请输入密码" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitLogin" block>登录</el-button>
      </el-form-item>
    </el-form>

    <p class="register-link">
      没有账号？<router-link to="/register">立即注册</router-link>
    </p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)

const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在3到15个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '至少输入6位密码', trigger: 'blur' }
  ]
}

const submitLogin = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.post('/api/login', loginForm.value)
        if (response.data.code === 200) {
          ElMessage.success('登录成功')
          localStorage.setItem('token', response.data.token)
          router.push('/')
        } else {
          ElMessage.error(response.data.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后再试')
        console.error(error)
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-form {
  width: 400px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}
</style>